package com.ruoyi.web.controller.project;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Store;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/project/store")
public class StoreController {
    @Autowired
    private IStoreService storeService;
    
    @Autowired
    private ISysUserService userService;

    @GetMapping("/{id}")
    public AjaxResult getStore(@PathVariable String id) {
        Store store = storeService.selectStoreById(id);
        return AjaxResult.success(store);
    }

    @GetMapping("/list")
    public AjaxResult listStores(Store store) {
        List<Store> list = storeService.selectStoreList(store);
        return AjaxResult.success(list);
    }

    @PostMapping("/add")
    public AjaxResult addStore(@RequestBody Store store) {
        // 1. 创建用户
        SysUser user = new SysUser();
        // 使用仓库名称作为用户名和昵称
        user.setUserName("store_" + store.getName().replaceAll("\\s+", "_"));
        user.setNickName(store.getName());
        // 设置初始密码
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        // 设置其他必要信息
//        user.setDeptId(100L); // 设置为默认部门ID
//        user.setEmail(user.getUserName() + "@example.com");
        user.setPhonenumber(""); // 手机号可为空
        user.setSex("0"); // 默认为男性
        user.setStatus("0"); // 默认为正常状态
        user.setDelFlag("0"); // 默认未删除
        
        // 2. 保存用户
        int userResult = userService.insertUser(user);
        
        if (userResult > 0) {
            // 3. 获取新创建用户的ID
            Long userId = user.getUserId();
            
            // 4. 设置仓库的用户ID
            store.setUserId(userId);
            
            // 5. 保存仓库信息
            int result = storeService.insertStore(store);
            return result > 0 ? AjaxResult.success() : AjaxResult.error("保存仓库信息失败");
        } else {
            return AjaxResult.error("创建关联用户失败");
        }
    }

    @PostMapping("update")
    public AjaxResult updateStore(@RequestBody Store store) {
        int result = storeService.updateStore(store);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteStore(@PathVariable String id) {
        int result = storeService.deleteStoreById(id);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @DeleteMapping("/batch")
    public AjaxResult deleteStores(@RequestBody String[] ids) {
        int result = storeService.deleteStoreByIds(ids);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }
} 